package com.newbee.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hhu.newbee.R;
import com.newbee.activity.tab.ConfigActivity;
import com.newbee.adapter.FriendsListvewAdapter;
import com.newbee.app.AppConfig;
import com.newbee.app.OnRefrushActivity;
import com.newbee.app.SpeechApp;
import com.newbee.http.ServerHttpUtil;
import com.newbee.round.CustomImageView;
import com.newbee.service.MainService;
import com.newbee.service.MainServiceKey;
import com.newbee.service.MainServiceTask;
import com.newbee.service.TaskType;
import com.newbee.smack.SmackClient;
import com.newbee.util.StringUtil;

public class AddFriendsActivity extends Activity implements OnClickListener,
		OnRefrushActivity
{

	private View mBack;
	private View mAdd;

	private EditText mText;

	public static final String ACCOUNT = "ACCOUNT";
	public static final int RESPONSE_CODE = 1;
	private String nickname;
	private String head;
	private CustomImageView mImageViewhead;
	private TextView mteTextViewemail;
	private TextView mTextViewnickname;
	private View userinfoView;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_add_friends);
		initLayout();
	}

	private void initLayout()
	{

		this.mBack = (View) this.findViewById(R.id.btn_add_friends_back);
		this.mBack.setOnClickListener(this);
		this.mAdd = (View) this.findViewById(R.id.btn_add_friend_sure);
		this.mAdd.setOnClickListener(this);
		this.mText = (EditText) this
				.findViewById(R.id.edittext_firends_account);
		this.findViewById(R.id.btn_add_friend_search).setOnClickListener(this);
		this.mteTextViewemail = (TextView) this.findViewById(R.id.add_email);
		this.mImageViewhead = (CustomImageView) this
				.findViewById(R.id.add_head);
		this.mTextViewnickname = (TextView) this
				.findViewById(R.id.add_nickname);
		userinfoView = this.findViewById(R.id.add_friend_info);
		userinfoView.setVisibility(View.GONE);

	}

	@Override
	public void onClick(View v)
	{

		switch (v.getId())
		{
		case R.id.btn_add_friend_sure:
		{

			String email = this.mText.getText().toString();
			if (email.length() <= 0)
			{
				Toast.makeText(this, "请输入好友的邮箱信息!", Toast.LENGTH_SHORT).show();
			}
			else if (StringUtil.isEmailFormat(email))
			{

				Intent intent = new Intent();
				intent.putExtra(ACCOUNT, this.mText.getText().toString()
						.replace("@", "#")
						+ "$" + nickname + "$" + head);
				this.setResult(RESPONSE_CODE, intent);
				this.finish();

			}
			else
			{
				Toast.makeText(this, "输入邮箱格式不正确!", Toast.LENGTH_SHORT).show();
			}
			break;
		}
		case R.id.btn_add_friends_back:
		{
			this.finish();
			break;
		}
		case R.id.btn_add_friend_search:
		{

			String email = this.mText.getText().toString();
			if (email.length() <= 0)
			{
				Toast.makeText(this, "请输入好友的邮箱信息!", Toast.LENGTH_SHORT).show();
			}
			else if (StringUtil.isEmailFormat(email))
			{

				Map<String, Object> paras = new HashMap<String, Object>();

				paras.put(MainServiceKey.EMAIL, email.replace("@", "#"));

				MainServiceTask mst = new MainServiceTask(
						TaskType.ADD_FRIEND_GET_NICKNAME, paras,
						AddFriendsActivity.class.getName());
				MainService.addActivityMap(AddFriendsActivity.class.getName(),
						this);
				MainService.addTaskQueue(mst);
				userinfoView.setVisibility(View.GONE);

			}
			else
			{
				Toast.makeText(this, "输入邮箱格式不正确!", Toast.LENGTH_SHORT).show();
			}
			break;

		}
		default:
			break;
		}

	}

	@Override
	protected void onDestroy()
	{

		MainService.removeActivity(AddFriendsActivity.class.getName());
		super.onDestroy();
	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public RtInfo refresh(int taskID, Object... paras)
	{
		switch (taskID)
		{
		case TaskType.ADD_FRIEND_GET_NICKNAME:
		{

			boolean re = (Boolean) paras[0];

			if (re == false)
			{
				Toast.makeText(this, "你所查找的账号不存在", Toast.LENGTH_LONG).show();
				return null;
			}

			nickname = (String) paras[1];
			head = ((String) paras[2]).split("\\.")[0];

			String username = (String) paras[3];
			final File file = new File(
					Environment.getExternalStorageDirectory()
							+ SpeechApp.HEAD_FILE + "/" + head + ".png");
			if (re)
			{
				SoftReference<Bitmap> softReference = FriendsListvewAdapter.bitmapMap
						.get(head);
				if (softReference != null)
				{

					Bitmap bitmap = softReference.get();
					mImageViewhead.setmSrc(bitmap);
					mImageViewhead.postInvalidate();

				}
				else
				{

					if (file.exists())
					{

						try
						{
							FileInputStream fis = new FileInputStream(file);
							Bitmap bitmap = BitmapFactory.decodeStream(fis);
							mImageViewhead.setmSrc(bitmap);
							mImageViewhead.postInvalidate();
							fis.close();

							FriendsListvewAdapter.bitmapMap.put(head,
									new SoftReference<Bitmap>(bitmap));
						}
						catch (FileNotFoundException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					else
					{
						new Thread(new Runnable()
						{

							public void run()
							{
								try
								{
									InputStream is = new URL(AppConfig.HTTP
											+ ServerHttpUtil.HEAD_dir + head
											+ ".png").openStream();

									Bitmap bitmap = BitmapFactory
											.decodeStream(is);
									is.close();
									mImageViewhead.setmSrc(bitmap);
									mImageViewhead.postInvalidate();
									FileOutputStream fis = new FileOutputStream(
											file);
									bitmap.compress(Bitmap.CompressFormat.PNG,
											100, fis);
									fis.close();
									FriendsListvewAdapter.bitmapMap.put(head,
											new SoftReference<Bitmap>(bitmap));
								}
								catch (FileNotFoundException e)
								{
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								catch (IOException e)
								{
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();

					}
				}

				this.mteTextViewemail.setText(mText.getText().toString());
				this.mTextViewnickname.setText(username);
				userinfoView.setVisibility(View.VISIBLE);

			}
			else
			{
				Toast.makeText(this, "你所查找的账号不存在", Toast.LENGTH_LONG).show();
			}
			break;
		}

		default:
			break;
		}

		return null;
	}
}
